package com.cskaoyan.aspect.promote;

import com.cskaoyan.bean.promote.base.PromoteParam;
import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.Date;

/**
 * @author liXiaoFei
 * @date 2021/10/19 17:35
 */

@Aspect
@Component
public class PromoteAspect {

    @Pointcut("execution(* com.cskaoyan.service.promote..query*(..))")
    public void PromoteQueryPointcut(){
    }

    @Pointcut("execution(* com.cskaoyan.service.promote..delete*(..))")
    public void PromoteDeletePointcut(){
    }

    @Pointcut("execution(* com.cskaoyan.service.promote..add*(..))")
    public void PromoteAddPointcut(){
    }

    @Around("PromoteQueryPointcut()")
    public Object aroundPromoteQuery(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        PromoteParam promoteParam = (PromoteParam) args[0];
        PageHelper.startPage(promoteParam.getPage(),promoteParam.getLimit());
        return joinPoint.proceed();
    }

    @Around("PromoteDeletePointcut()")
    public Object aroundPromoteDelete(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Object bean = args[0];
        Class<?> clazz = bean.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            field.setAccessible(true);
            if ("deleted".equals(name)) {
                new PropertyDescriptor(name, clazz).getWriteMethod().invoke(bean, true);
            }
        }
        return joinPoint.proceed();
    }


    @Around("PromoteAddPointcut()")
    public Object aroundPromoteAdd(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Object bean = args[0];
        Class<?> clazz = bean.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Date date = new Date(System.currentTimeMillis());
        for (Field field : fields) {
            String name = field.getName();
            field.setAccessible(true);
            if (("addTime".equals(name) && field.get(bean) == null) || "updateTime".equals(name)) {
                new PropertyDescriptor(name, clazz).getWriteMethod().invoke(bean, date);
            }
        }
        return joinPoint.proceed();
    }



}
